package com.ruangong.GitClient.YanZhaoWang;

import android.os.Build;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;

import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;

import com.ruangong.GitClient.R;
public class YanZhaoWang {
    /**
     * 省份代码和省份名称的映射
     */
    private static final Map<String, Integer> CODE_PROVINCE;

    /**
     * 省份代码和大学列表的映射
     */
    public static Map<Integer, List<String>> PROVINCE_CODE_UNIVERSITY = new HashMap<>();

    static {
        CODE_PROVINCE = initializeProvinceCode();
    }
    public static void main(String[] args) throws Exception {
        populateUniversities();
        printUniversities();


    }
    /**
     * 初始化省份代码和省份名称的映射
     *
     * @return 省份代码和省份名称的映射
     */
    private static Map<String, Integer> initializeProvinceCode() {
        String data = "11 北京,12 天津,13 河北,14 山西,15 内蒙古,"
                + "21 辽宁,22 吉林,23 黑龙江,"
                + "31 上海,32 江苏,33 浙江,34 安徽,35 福建,36 江西,37 山东,"
                + "41 河南,42 湖北,43 湖南,44 广东,45 广西,46 海南,"
                + "50 重庆,51 四川,52 贵州,53 云南,54 西藏,"
                + "61 陕西,62 甘肃,63 青海,64 宁夏,65 新疆";
        Map<String, Integer> provinceCodeMap = new HashMap<>();
        String[] entries = data.split(",");
        for (String entry : entries) {
            String[] parts = entry.trim().split(" ");
            provinceCodeMap.put(parts[1], Integer.parseInt(parts[0]));
        }
        return provinceCodeMap;
    }

    /**
     * 通过名称找省份代码
     *
     * @return 省份代码
     */
    public static int findProvinceCodeByName(String provinceName) {

        // 查找给定省份名称对应的省份代码，并返回结果
        Integer provinceCode = CODE_PROVINCE.get(provinceName);
        return provinceCode != null ? provinceCode : -1; // 如果找到对应的省份代码，则返回，否则返回 -1 表示未找到
    }


    /**
     * 从网站上获取大学列表并保存到本地
     *
     * @throws Exception 读取网页异常
     */
    public static void populateUniversities() throws Exception {
        int[] ssdm = {11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65};
        for (int i : ssdm) {
            List<String> temp = getUniversitiesByProvinceCode(i);
            PROVINCE_CODE_UNIVERSITY.put(i, temp);

        }
        // 创建Gson对象实例
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        // 将Map转换为JSON字符串
        String json = gson.toJson(PROVINCE_CODE_UNIVERSITY);

        // 写JSON字符串到文件
        try (Writer writer = new FileWriter("app\\src\\main\\java\\com\\ruangong\\GitClient\\YanZhaoWang\\Province_University.json")) {
            writer.write(json);
        }

        System.out.println("JSON file was created successfully.");
    }

    /**
     * 从网站上获取大学列表
     *
     * @param provinceCode 省份代码
     * @return 大学列表
     * @throws IOException 读取网页异常
     */
    public static List<String> getUniversitiesByProvinceCode(Integer provinceCode) throws IOException {
        List<String> universities = new ArrayList<>();
        for (int num = 0; num <= 200; num += 20) {
            String url = "https://yz.chsi.com.cn/sch/search.do?ssdm=" + provinceCode + "&start=" + num;
            Document doc = Jsoup.connect(url).get();
            Elements university = doc.select("div.sch-title > a");
            if (university.isEmpty()) {
                break;
            }
            for (Element element : university) {
                universities.add(element.text());
            }
        }
        return universities;
    }

    /**
     * 从本地获取大学列表
     * @param provinceCode 省份代码
     * @return 大学列表
     * @throws IOException 读取文件异常
     */
    public static List<String> getUniversitiesByProvinceCodeLocally(Integer provinceCode) throws IOException{
        Gson gson = new Gson();

        FileReader reader = new FileReader("app\\src\\main\\java\\com\\ruangong\\GitClient\\YanZhaoWang\\Province_University.json");
            // 创建类型指示器
            Type mapType = new TypeToken<Map<Integer, List<String>>>() {}.getType();

            // 将JSON转换成Map
            Map<Integer, List<String>> map = gson.fromJson(reader, mapType);

            // 输出Map内容
            System.out.println(map);
            return map.get(provinceCode);


    }


    /**
     * 打印大学列表
     */
    public static void printUniversities() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            PROVINCE_CODE_UNIVERSITY.forEach((k, v) -> System.out.println("Province Code: " + CODE_PROVINCE.get(k) + ", Universities: " + v));
        }
    }
    /**
     * 从本地获取研究学科名称列
     * @param ResearchCode 研究学科代码
     * @return 学科名称
     * @throws IOException 读取文件异常
     */
    public static String getResearchDisciplineLocally(String ResearchCode) throws IOException{
        Gson gson = new Gson();

        FileReader reader = new FileReader("app\\src\\main\\java\\com\\ruangong\\GitClient\\YanZhaoWang\\Research_Discipline_Code.json");
        // 创建类型指示器
        Type mapType = new TypeToken<Map<String, String>>() {}.getType();

        // 将JSON转换成Map
        Map<String, String> map = gson.fromJson(reader, mapType);

        // 输出Map内容
//        System.out.println(map.keySet());
        return map.get(ResearchCode);
    }

    /**
     * 从本地获取研究学科代码列表
     * @return 研究学科代码set集合
     * @throws IOException 读取文件异常
     */
    public static Set<String> getResearchDisciplineAllCodeLocally() throws IOException{
        Gson gson = new Gson();

        FileReader reader = new FileReader("app\\src\\main\\java\\com\\ruangong\\GitClient\\YanZhaoWang\\Research_Discipline_Code.json");
        // 创建类型指示器
        Type mapType = new TypeToken<Map<String, String>>() {}.getType();

        // 将JSON转换成Map
        Map<String, String> map = gson.fromJson(reader, mapType);

//        System.out.println();
        return map.keySet();
    }


    /**
     * 打印专业列表
     * @param ssdm 省市代码
     * @param yixkdm 研究学科代码
     * @param university 大学名称
     */
    public static List<Major> getMajorList(int ssdm,String yixkdm,String university)
    {
        List<Major> majorList = new java.util.ArrayList<>();
        try {
            String url = "https://yz.chsi.com.cn/zsml/querySchAction.do?ssdm=" + ssdm + "&dwmc=" + university + "&mldm=&mlmc=&yjxkdm=" + yixkdm + "&xxfs=&zymc=";
            // 连接到网页
            Document doc = Jsoup.connect(url).get();
            // 解析网页标题
            String title = doc.title();
            System.out.println("标题: " + title);

            System.out.println(university);
            // 如果你想提取表格中的数据
            Elements tables = doc.select("table");
            for (Element table : tables) {
                Elements rows = table.select("tr");
                for (Element row : rows) {
                    List<String> major = new java.util.ArrayList<>();
                    Elements cols = row.select("td");
                    for (Element col : cols) {
                        if (!col.select("script").isEmpty()) {
                            Elements scripts = col.select("script");
                            for (Element script : scripts) {
                                String data = script.data();
                                String[] split = data.split("document.write\\(cutString\\('");
                                for (String s : split) {
                                    if (s.contains("',6)")) {
                                        String[] split1 = s.split("',6\\)\\);");
                                        major.add(split1[0]);
                                    }
                                }

                            }
                        } else {
                            major.add(col.text());
                        }
                    }
                    if (!major.isEmpty()) {
                        majorList.add(new Major(major.get(0), major.get(1), major.get(2), major.get(3), major.get(4), major.get(5), major.get(6), major.get(7), major.get(8)));
                    }
                }
            }
//            System.out.println(doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return majorList;
//        for (Major major : majorList) {
//            System.out.println(major);
//        }
    }
    // 解析JSON文件并将值存储为String数组的函数
    public static List<String> getSubjectList(Context context) {
        Log.d("FileUtils", "11");
        List<String> values = new ArrayList<>();
        try {
            // 从文件中读取JSON数据
            Log.d("FileUtils", "Reading JSON data from resource file.");
            InputStream inputStream = context.getResources().openRawResource(R.raw.research_discipline_code);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                String jsonString = stringBuilder.toString();
                // 关闭读取器
                reader.close();
                // 解析JSON数据
                JsonParser parser = new JsonParser();
                JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
                // 从JsonObject中获取所有的值
                for (String key : jsonObject.keySet()) {
                    JsonElement element = jsonObject.get(key);
                    values.add(element.getAsString());
                }
                Log.d("FileUtils", "Successfully read JSON data.");
            } else {
                Log.e("FileUtils", "Input stream is null. File not found.");
            }
        } catch (IOException e) {
            Log.e("FileUtils", "Error reading JSON data: " + e.getMessage());
            e.printStackTrace();
        }

        return values;
    }



    public static String getSubjectCode(String subjectName) {
        String extracted = null;
        Pattern pattern = Pattern.compile("\\((\\d+)\\)");
        Matcher matcher = pattern.matcher(subjectName);

        if (matcher.find()) {
            extracted = matcher.group(1);
        }

        return extracted;
    }
}
